// pages/input_information/index.js
import { qualificateList, qualificateDetail, qualificateApply, qualificateData } from '../../api/qualificate.js'

import { uploadFile } from '../../api/common.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pid:'',
    applyId: '',
    userId:'',
    medalIndex:-1, // 资质类型
    medalArray:[],//资质数组
    count: 3, // 图片总数
    imageList: [], // 图片
    imgUrl: [], // 保存后的图片地址
    haveQualified: [], // 已拥有资质列表
    sendState:0,
    qualificateId: '', // 需要认证指定资质的ID
    stop:false, // 是否停留在当前页
    add:false //是否是新增
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.stop) {
      this.setData({ stop: true })
    }
    this.setData({ userId: options.uid, pid: options.pid })
    this._qualificateData(options.pid)
    this._qualificateDetail(options.pid)
    if (options.qualificateId) {
      this.setData({ qualificateId: options.qualificateId })
    }
    this._qualificateList()
    if (options.applyId) {
      this.setData({ applyId: options.applyId })
    }
    if (options.add) {
      this.setData({ add: options.add })
    }
    
  },
  //获取审核状态
  _qualificateData(id){
    qualificateData(id).then(res=>{
      console.log(res)
      //res.data不为空 状态不为认证成功 APPlyId为空（非重新认证）时进入
      //res.data.status,认证状态：1=认证成功；2=认证失败；3=认证中
      let d = res.data||'';
      if (d != ''){ // 近期有认证过
        if (this.data.stop){ // 需要停留在当前页的
        } else if (d.status != 1) {//认证失败或者认证中
          wx.redirectTo({
            url: `/pages/state_page/index?pid=${this.data.pid}&status=${d.status}&applyId=${d.applyId}`,
          })
        }
        // console.log(d)
        if (!this.data.add) {
          this.setData({ applyId: d.applyId })
        }
      }
    })
  },

  // 获取列表
  _qualificateList(){
    let { qualificateId} = this.data
    qualificateList().then(res => {
      this.setData({ medalArray: res.data})
      if (qualificateId!=''){
        res.data.forEach((e,i)=>{
          if (e.qualificateId == qualificateId){
            this.setData({ medalIndex:i})
          }
        })
      }
    })
  },

  // 获取资质
  _qualificateDetail(id){
    qualificateDetail(id).then(res=>{
      this.setData({ haveQualified: res.data })
    })
  },
  bindMedalArrayChange(e){
    let name = ''
    let index = e.detail.value;
    this.data.haveQualified.forEach(e=>{
      if (e.qualificateId == this.data.medalArray[index].qualificateId){
        name = e.name
      }
    })
    if (name) {
      wx.showModal({
        title: `已拥有“${name}”资质`,
        content: '是否选择其它需要认证的资质或者返回',
        showCancel: true,//是否显示取消按钮
        cancelText: "确定",
        cancelColor: '#999999',
        confirmText: "返回",
        confirmColor: '#000000',
        success: function (res) {
          if (res.cancel) {
            //点击确定
          } else {
            //点击返回上一页
            wx.navigateBack(1)
          }
        },
        fail: function (res) { },//接口调用失败的回调函数
        complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
      })
    } else {
      this.setData({ medalIndex: index })
      this.check()
    }
  },

  addImage() { // 选择图片
    let _this = this;
    let { count,imageList} = this.data
    wx.chooseImage({
      count: count - imageList.length, // 可用数-当前数
      success: res => {
        _this.setData({ imageList: [...imageList, ...res.tempFilePaths] })
        res.tempFilePaths.forEach(e=>{
          _this._uploadFile(e)
        })
      }
    })
  },

  // 文件上传
  _uploadFile(img) {
    uploadFile(img, 'file', res => { // 图片上传成功
      res.data = JSON.parse(res.data)
      if (res.data.code != 0) {
        this.showToast('图片上传失败', 'none')
      } else {
        this.setData({ ['imgUrl[' + this.data.imgUrl.length + ']']: res.data.url })
      }
      this.check()
    }, err => { // 图片上传失败
      this.showToast('图片上传失败', 'none')
      this.check()
    })
  },
  delImage(e) { // 删除图片
    let index = e.currentTarget.dataset.index;
    // console.log(index)
    let _this = this;
    wx.showModal({
      title: '删除图片',
      content: '确定要删除第' + Number(index + 1) + '张图片？',
      showCancel: true, //是否显示取消按钮
      cancelText: "否", //默认是“取消”
      cancelColor: '#1781FF', //取消文字的颜色
      confirmText: "是", //默认是“确定”
      confirmColor: '#1781FF', //确定文字的颜色
      success: function (res) {
        if (!res.cancel) {
          //点击确定
          let imageList = _this.data.imageList
          imageList.splice(index, 1)
          let imgUrl = _this.data.imgUrl
          imgUrl.splice(index, 1)
          _this.setData({
            imageList,
            imgUrl
          })
        }
      }
    })
  },

  //数据验证
  check() {
    let { medalIndex, imgUrl } = this.data
    if (medalIndex == -1) {
      this.setData({ sendState: 1 })
    } else if (imgUrl.length<=0) {
      this.setData({ sendState: 2 })
    } else {
      this.setData({ sendState: 0 })
    }
  },

  //提交认证信息
  send() {
    this.check()
    let { sendState,applyId, pid, medalIndex, medalArray, imgUrl, qualificateId} = this.data;
    if (sendState == 1) {
      wx.showToast({title: '请选择资质类型',icon: 'none'})
    } else if (sendState == 2) {
      wx.showToast({title: '请上传您于该资质相关的运动图片',icon: 'none'})
    } else {
      let obj = {
        participantId: pid,
        qualificateId: medalArray[medalIndex].qualificateId,
        imageList: imgUrl
      }
      if (applyId != '') {
        obj.applyId = applyId
      }
      qualificateApply(obj).then(res => {
        console.log(res)
        if (res.code == 0) {
          if (qualificateId == '') {
            wx.redirectTo({
              url: '/pages/state_page/index?pid=' + pid,
            })
          } else {
            wx.navigateBack()
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})